package social.hub.impl.jersey.api;

import static social.hub.api.linkedin.LinkedInConstants.*;

import java.util.List;

import social.hub.api.linkedin.LinkedInApi;
import social.hub.api.linkedin.LinkedInPublication;
import social.hub.api.linkedin.LinkedinProfile;
import social.hub.impl.jersey.util.ClientFactory;
import social.hub.util.UrlBuilder;

import com.sun.jersey.api.client.Client;

public class JerseyLinkedInApi implements LinkedInApi {

	private final String accessToken;
	private final Client client;

	public JerseyLinkedInApi(String accessToken) {
		client = ClientFactory.createClient();
		this.accessToken = accessToken;
	}

	public LinkedinProfile getProfile() {
		return getProfile(SELF_ID);
	}

	@Override
	public LinkedinProfile getProfile(String linkedinId) {
		String url = buildUrl(PROFILE_URL, linkedinId);
		return client.resource(url).get(LinkedinProfile.class);
	}

	@Override
	public List<LinkedInPublication> getPublications() {
		return getPublications(SELF_ID);
	}

	@Override
	public List<LinkedInPublication> getPublications(String linkedinId) {

		String url = buildUrl(PUBLICATIONS_URL, linkedinId);

		LinkedinProfile profile = client.resource(url).get(LinkedinProfile.class);

		List<LinkedInPublication> result = null;

		if (profile.getPublicationList() != null) {
			result = profile.getPublicationList().getPublicationList();
		}

		return result;

	}

	private String buildUrl(String baseUrl, String linkedinId) {
		return new UrlBuilder(baseUrl).addUrlParan("profileId", linkedinId).addQueryParan("access_token", accessToken)
				.toString();
	}

}